<template>
  <div class="behavior-analysis-page">


    <!-- 行为趋势分析图 -->
    <el-row :gutter="24" class="charts-row">
      <el-col :xs="24" :xl="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><TrendCharts /></el-icon>
                键盘频率趋势
              </span>
              <div class="card-actions">
                <!-- 时间范围选择 -->
                <el-select
                  v-model="keyboardTimeRange"
                  size="small"
                  style="width: 80px; margin-right: 8px"
                  @change="handleKeyboardFilterChange"
                >
                  <el-option label="日" value="day" />
                  <el-option label="周" value="week" />
                  <el-option label="月" value="month" />
                </el-select>

                <!-- 日期范围筛选 -->
                <template v-if="keyboardTimeRange === 'day'">
                  <el-date-picker
                    v-model="keyboardDateRange"
                    type="daterange"
                    size="small"
                    style="width: 200px; margin-right: 8px"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @change="handleKeyboardFilterChange"
                  />
                </template>

                <!-- 周范围筛选 -->
                <template v-if="keyboardTimeRange === 'week'">
                  <el-date-picker
                    v-model="keyboardWeekRange"
                    type="week"
                    size="small"
                    style="width: 150px; margin-right: 8px"
                    placeholder="选择周"
                    format="YYYY 第 ww 周"
                    value-format="YYYY-MM-DD"
                    @change="handleKeyboardFilterChange"
                  />
                  <span style="margin-right: 8px; font-size: 12px; color: #666;">至</span>
                  <el-date-picker
                    v-model="keyboardWeekRangeEnd"
                    type="week"
                    size="small"
                    style="width: 150px; margin-right: 8px"
                    placeholder="结束周"
                    format="YYYY 第 ww 周"
                    value-format="YYYY-MM-DD"
                    @change="handleKeyboardFilterChange"
                  />
                </template>

                <!-- 对比模式选择 -->
                <el-select
                  v-model="keyboardCompareMode"
                  size="small"
                  style="width: 120px; margin-right: 8px"
                  @change="handleKeyboardFilterChange"
                >
                  <el-option label="个人数据" value="personal" />
                  <el-option label="两人对比" value="compare" />
                  <el-option label="个人vs部门" value="vs_dept" />
                </el-select>

                <!-- 用户选择（根据对比模式显示不同的选择器） -->
                <template v-if="keyboardCompareMode === 'personal'">
                  <el-select
                    v-model="keyboardSelectedUser"
                    size="small"
                    style="width: 120px"
                    placeholder="选择用户"
                    @change="handleKeyboardFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>

                <template v-if="keyboardCompareMode === 'compare'">
                  <el-select
                    v-model="keyboardUser1"
                    size="small"
                    style="width: 100px; margin-right: 4px"
                    placeholder="用户1"
                    @change="handleKeyboardFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                  <el-select
                    v-model="keyboardUser2"
                    size="small"
                    style="width: 100px"
                    placeholder="用户2"
                    @change="handleKeyboardFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>

                <template v-if="keyboardCompareMode === 'vs_dept'">
                  <el-select
                    v-model="keyboardSelectedUser"
                    size="small"
                    style="width: 100px; margin-right: 4px"
                    placeholder="用户"
                    @change="handleKeyboardFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                  <el-select
                    v-model="keyboardSelectedDept"
                    size="small"
                    style="width: 100px"
                    placeholder="部门"
                    @change="handleKeyboardFilterChange"
                  >
                    <el-option
                      v-for="dept in availableDepts"
                      :key="dept.id"
                      :label="dept.name"
                      :value="dept.id"
                    />
                  </el-select>
                </template>
              </div>
            </div>
          </template>
          <div class="chart-content">
            <div class="chart-legend">
              <div class="legend-item">
                <span class="legend-color" style="background: #409EFF"></span>
                <span>当前用户</span>
              </div>
              <div class="legend-item" v-if="keyboardCompareMode === 'compare'">
                <span class="legend-color" style="background: #67C23A"></span>
                <span>对比用户</span>
              </div>
              <div class="legend-item" v-if="keyboardCompareMode === 'vs_dept'">
                <span class="legend-color" style="background: #E6A23C"></span>
                <span>部门平均</span>
              </div>
            </div>
            <div class="chart-area">
              <svg width="100%" height="180" viewBox="0 0 400 180">
                <!-- 渐变定义 -->
                <defs>
                  <pattern id="modernGrid" width="40" height="36" patternUnits="userSpaceOnUse">
                    <path d="M 40 0 L 0 0 0 36" fill="none" stroke="#e2e8f0" stroke-width="0.5" opacity="0.6"/>
                  </pattern>
                  <linearGradient id="keyboardGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#409EFF;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#409EFF;stop-opacity:0.05" />
                  </linearGradient>
                  <linearGradient id="compareGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#67C23A;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#67C23A;stop-opacity:0.05" />
                  </linearGradient>
                  <linearGradient id="deptGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#E6A23C;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#E6A23C;stop-opacity:0.05" />
                  </linearGradient>
                </defs>
                <rect width="100%" height="100%" fill="url(#modernGrid)" />

                <!-- 键盘事件趋势区域填充 -->
                <polygon
                  v-if="keyboardTrendData.keyboard.length > 0"
                  fill="url(#keyboardGradient)"
                  :points="`${keyboardTrendData.keyboard.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (keyboardTrendData.keyboard.length - 1) * 40},160 20,160`"
                />

                <!-- 键盘事件趋势线 -->
                <polyline
                  v-if="keyboardTrendData.keyboard.length > 0"
                  fill="none"
                  stroke="#409EFF"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="keyboardTrendData.keyboard.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <!-- 对比区域填充（根据模式显示） -->
                <polygon
                  v-if="keyboardCompareMode === 'compare' && keyboardTrendData.compare"
                  fill="url(#compareGradient)"
                  :points="`${keyboardTrendData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (keyboardTrendData.compare.length - 1) * 40},160 20,160`"
                />

                <polygon
                  v-if="keyboardCompareMode === 'vs_dept' && keyboardTrendData.compare"
                  fill="url(#deptGradient)"
                  :points="`${keyboardTrendData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (keyboardTrendData.compare.length - 1) * 40},160 20,160`"
                />

                <!-- 对比线（根据模式显示） -->
                <polyline
                  v-if="keyboardCompareMode === 'compare' && keyboardTrendData.compare"
                  fill="none"
                  stroke="#67C23A"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="keyboardTrendData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <polyline
                  v-if="keyboardCompareMode === 'vs_dept' && keyboardTrendData.compare"
                  fill="none"
                  stroke="#E6A23C"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="keyboardTrendData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <!-- 数据点 -->
                <circle
                  v-for="(item, index) in keyboardTrendData.keyboard"
                  :key="`point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#409EFF"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <!-- 对比数据点 -->
                <circle
                  v-if="keyboardCompareMode === 'compare' && keyboardTrendData.compare"
                  v-for="(item, index) in keyboardTrendData.compare"
                  :key="`compare-point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#67C23A"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <circle
                  v-if="keyboardCompareMode === 'vs_dept' && keyboardTrendData.compare"
                  v-for="(item, index) in keyboardTrendData.compare"
                  :key="`dept-point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#E6A23C"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <!-- 数值标签 -->
                <text
                  v-for="(item, index) in keyboardTrendData.keyboard"
                  :key="`label-${index}`"
                  :x="20 + index * 40"
                  :y="item.y - 8"
                  text-anchor="middle"
                  fill="#666"
                  font-size="10"
                >
                  {{ item.count }}
                </text>
              </svg>
            </div>
            <div class="chart-x-axis">
              <span
                v-for="item in keyboardTrendData.keyboard"
                :key="item.time"
              >
                {{ item.time }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :xl="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><DataAnalysis /></el-icon>
                鼠标频率趋势
              </span>
              <div class="card-actions">
                <!-- 时间范围选择 -->
                <el-select
                  v-model="mouseTimeRange"
                  size="small"
                  style="width: 80px; margin-right: 8px"
                  @change="handleMouseFilterChange"
                >
                  <el-option label="日" value="day" />
                  <el-option label="周" value="week" />
                  <el-option label="月" value="month" />
                </el-select>

                <!-- 日期范围筛选 -->
                <template v-if="mouseTimeRange === 'day'">
                  <el-date-picker
                    v-model="mouseDateRange"
                    type="daterange"
                    size="small"
                    style="width: 200px; margin-right: 8px"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @change="handleMouseFilterChange"
                  />
                </template>

                <!-- 周范围筛选 -->
                <template v-if="mouseTimeRange === 'week'">
                  <el-date-picker
                    v-model="mouseWeekRange"
                    type="week"
                    size="small"
                    style="width: 150px; margin-right: 8px"
                    placeholder="选择周"
                    format="YYYY 第 ww 周"
                    value-format="YYYY-MM-DD"
                    @change="handleMouseFilterChange"
                  />
                  <span style="margin-right: 8px; font-size: 12px; color: #666;">至</span>
                  <el-date-picker
                    v-model="mouseWeekRangeEnd"
                    type="week"
                    size="small"
                    style="width: 150px; margin-right: 8px"
                    placeholder="结束周"
                    format="YYYY 第 ww 周"
                    value-format="YYYY-MM-DD"
                    @change="handleMouseFilterChange"
                  />
                </template>

                <!-- 对比模式选择 -->
                <el-select
                  v-model="mouseCompareMode"
                  size="small"
                  style="width: 120px; margin-right: 8px"
                  @change="handleMouseFilterChange"
                >
                  <el-option label="个人数据" value="personal" />
                  <el-option label="两人对比" value="compare" />
                  <el-option label="个人vs部门" value="vs_dept" />
                </el-select>

                <!-- 用户选择（根据对比模式显示不同的选择器） -->
                <template v-if="mouseCompareMode === 'personal'">
                  <el-select
                    v-model="mouseSelectedUser"
                    size="small"
                    style="width: 120px"
                    placeholder="选择用户"
                    @change="handleMouseFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>

                <template v-if="mouseCompareMode === 'compare'">
                  <el-select
                    v-model="mouseUser1"
                    size="small"
                    style="width: 100px; margin-right: 4px"
                    placeholder="用户1"
                    @change="handleMouseFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                  <el-select
                    v-model="mouseUser2"
                    size="small"
                    style="width: 100px"
                    placeholder="用户2"
                    @change="handleMouseFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                </template>

                <template v-if="mouseCompareMode === 'vs_dept'">
                  <el-select
                    v-model="mouseSelectedUser"
                    size="small"
                    style="width: 100px; margin-right: 4px"
                    placeholder="用户"
                    @change="handleMouseFilterChange"
                  >
                    <el-option
                      v-for="user in availableUsers"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                    />
                  </el-select>
                  <el-select
                    v-model="mouseSelectedDept"
                    size="small"
                    style="width: 100px"
                    placeholder="部门"
                    @change="handleMouseFilterChange"
                  >
                    <el-option
                      v-for="dept in availableDepts"
                      :key="dept.id"
                      :label="dept.name"
                      :value="dept.id"
                    />
                  </el-select>
                </template>
              </div>
            </div>
          </template>
          <div class="chart-content">
            <div class="chart-legend">
              <div class="legend-item">
                <span class="legend-color" style="background: #409EFF"></span>
                <span>{{ getMouseLegendLabel('primary') }}</span>
              </div>
              <div class="legend-item" v-if="mouseCompareMode === 'compare'">
                <span class="legend-color" style="background: #67C23A"></span>
                <span>{{ getMouseLegendLabel('compare') }}</span>
              </div>
              <div class="legend-item" v-if="mouseCompareMode === 'vs_dept'">
                <span class="legend-color" style="background: #E6A23C"></span>
                <span>{{ getMouseLegendLabel('compare') }}</span>
              </div>
            </div>
            <div class="chart-area">
              <svg width="100%" height="180" viewBox="0 0 400 180">
                <!-- 渐变定义 -->
                <defs>
                  <pattern id="mouseModernGrid" width="40" height="36" patternUnits="userSpaceOnUse">
                    <path d="M 40 0 L 0 0 0 36" fill="none" stroke="#e2e8f0" stroke-width="0.5" opacity="0.6"/>
                  </pattern>
                  <linearGradient id="mouseGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#409EFF;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#409EFF;stop-opacity:0.05" />
                  </linearGradient>
                  <linearGradient id="mouseCompareGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#67C23A;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#67C23A;stop-opacity:0.05" />
                  </linearGradient>
                  <linearGradient id="mouseDeptGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#E6A23C;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#E6A23C;stop-opacity:0.05" />
                  </linearGradient>
                </defs>
                <rect width="100%" height="100%" fill="url(#mouseModernGrid)" />

                <!-- 鼠标事件趋势区域填充 -->
                <polygon
                  v-if="mouseHeatmapData.mouse && mouseHeatmapData.mouse.length > 0"
                  fill="url(#mouseGradient)"
                  :points="`${mouseHeatmapData.mouse.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (mouseHeatmapData.mouse.length - 1) * 40},160 20,160`"
                />

                <!-- 主趋势线 -->
                <polyline
                  v-if="mouseHeatmapData.mouse && mouseHeatmapData.mouse.length > 0"
                  fill="none"
                  stroke="#409EFF"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="mouseHeatmapData.mouse.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <!-- 对比区域填充（根据模式显示） -->
                <polygon
                  v-if="mouseCompareMode === 'compare' && mouseHeatmapData.compare"
                  fill="url(#mouseCompareGradient)"
                  :points="`${mouseHeatmapData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (mouseHeatmapData.compare.length - 1) * 40},160 20,160`"
                />

                <polygon
                  v-if="mouseCompareMode === 'vs_dept' && mouseHeatmapData.compare"
                  fill="url(#mouseDeptGradient)"
                  :points="`${mouseHeatmapData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')} ${20 + (mouseHeatmapData.compare.length - 1) * 40},160 20,160`"
                />

                <!-- 对比线（根据模式显示） -->
                <polyline
                  v-if="mouseCompareMode === 'compare' && mouseHeatmapData.compare"
                  fill="none"
                  stroke="#67C23A"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="mouseHeatmapData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <polyline
                  v-if="mouseCompareMode === 'vs_dept' && mouseHeatmapData.compare"
                  fill="none"
                  stroke="#E6A23C"
                  stroke-width="3"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  :points="mouseHeatmapData.compare.map((item, index) => `${20 + index * 40},${item.y}`).join(' ')"
                />

                <!-- 数据点 -->
                <circle
                  v-if="mouseHeatmapData.mouse && mouseHeatmapData.mouse.length > 0"
                  v-for="(item, index) in mouseHeatmapData.mouse"
                  :key="`mouse-point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#409EFF"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <!-- 对比数据点 -->
                <circle
                  v-if="mouseCompareMode === 'compare' && mouseHeatmapData.compare"
                  v-for="(item, index) in mouseHeatmapData.compare"
                  :key="`mouse-compare-point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#67C23A"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <circle
                  v-if="mouseCompareMode === 'vs_dept' && mouseHeatmapData.compare"
                  v-for="(item, index) in mouseHeatmapData.compare"
                  :key="`mouse-dept-point-${index}`"
                  :cx="20 + index * 40"
                  :cy="item.y"
                  r="5"
                  fill="#E6A23C"
                  stroke="white"
                  stroke-width="2"
                  class="data-point"
                />

                <!-- 数值标签 -->
                <text
                  v-if="mouseHeatmapData.mouse && mouseHeatmapData.mouse.length > 0"
                  v-for="(item, index) in mouseHeatmapData.mouse"
                  :key="`mouse-label-${index}`"
                  :x="20 + index * 40"
                  :y="item.y - 8"
                  text-anchor="middle"
                  fill="#666"
                  font-size="10"
                >
                  {{ item.count }}
                </text>
              </svg>
            </div>
            <div class="chart-x-axis">
              <span
                v-if="mouseHeatmapData.mouse && mouseHeatmapData.mouse.length > 0"
                v-for="item in mouseHeatmapData.mouse"
                :key="item.time"
              >
                {{ item.time }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><DataLine /></el-icon>
            详细统计数据
          </span>
        </div>
      </template>

      <el-table :data="behaviorStats" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="client_name" label="客户端名称" width="150" />
        <el-table-column prop="hostname" label="主机名" width="150" />
        <el-table-column prop="timestamp" label="时间戳" width="180">
          <template #default="{ row }">
            {{ new Date(row.timestamp).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="keyboard_count" label="键盘操作次数" width="140" />
        <el-table-column prop="mouse_count" label="鼠标操作次数" width="140" />
        <el-table-column prop="active_time" label="活跃时间(秒)" width="120" />
        <el-table-column prop="idle_time" label="空闲时间(秒)" width="120" />
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadBehaviorData"
          @current-change="loadBehaviorData"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { TrendCharts, DataAnalysis, DataLine } from '@element-plus/icons-vue'
import { behaviorAPI } from '@/services/api.js'
import { useClientsStore } from '@/stores/clients'
import { dashboardService, departmentsService } from '@/services/dataService.js'

// Store
const clientsStore = useClientsStore()

// 响应式数据
const loading = ref(false)

// 仪表板趋势图数据
const keyboardTimeRange = ref('day')
const keyboardCompareMode = ref('personal')
const keyboardSelectedUser = ref('')
const keyboardUser1 = ref('')
const keyboardUser2 = ref('')
const keyboardSelectedDept = ref('')
// 新增日期和周范围筛选
const keyboardDateRange = ref([])
const keyboardWeekRange = ref('')
const keyboardWeekRangeEnd = ref('')

const mouseTimeRange = ref('day')
const mouseCompareMode = ref('personal')
const mouseSelectedUser = ref('')
const mouseUser1 = ref('')
const mouseUser2 = ref('')
const mouseSelectedDept = ref('')
// 新增日期和周范围筛选
const mouseDateRange = ref([])
const mouseWeekRange = ref('')
const mouseWeekRangeEnd = ref('')

// 用户和部门数据
const availableUsers = ref([])
const availableDepts = ref([])

// 图表数据
const keyboardTrendData = ref({
  keyboard: [],
  mouse: [],
  compare: null
})
const mouseHeatmapData = ref({
  mouse: [],
  compare: null,
  maxActivity: 0,
  avgActivity: 0
})

// 筛选表单（保留用于兼容模板）
const filterForm = reactive({
  analysisType: 'individual',
  timeRange: 'today',
  customDateRange: null,
  selectedUser: null,
  selectedUsers: []
})

// 行为统计数据
const behaviorStats = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 用户列表 - 从store获取真实数据
const userList = computed(() => {
  // clientsStore.clients 是一个 Map，需要转换为数组
  const clientsArray = Array.from(clientsStore.clients.values())
  return clientsArray.map(client => ({
    id: client.id,
    name: client.name || `客户端-${client.id}`,
    department: client.department?.name || '未分配部门'
  }))
})

// 处理分析类型变化
const handleAnalysisTypeChange = () => {
  if (filterForm.analysisType === 'individual') {
    filterForm.selectedUsers = []
    if (availableUsers.value.length > 0) {
      filterForm.selectedUser = availableUsers.value[0]?.id
    }
  } else {
    filterForm.selectedUser = null
    if (availableUsers.value.length >= 2) {
      filterForm.selectedUsers = availableUsers.value.slice(0, 2).map(u => u.id)
    }
  }
  loadBehaviorData()
}

// 加载行为数据（兼容模板调用）
const loadBehaviorData = async () => {
  // 同时加载图表数据和统计数据
  await Promise.all([
    loadKeyboardTrendData(),
    loadMouseHeatmapData(),
    loadBehaviorStats()
  ])
}

// 获取效率标签类型
const getEfficiencyType = (efficiency) => {
  if (efficiency >= 80) return 'success'
  if (efficiency >= 60) return 'warning'
  return 'danger'
}

// 加载键盘趋势数据
const loadKeyboardTrendData = async () => {
  try {
    const params = {
      timeRange: keyboardTimeRange.value,
      compareMode: keyboardCompareMode.value
    }

    // 添加日期和周范围筛选参数
    if (keyboardTimeRange.value === 'day' && keyboardDateRange.value && keyboardDateRange.value.length === 2) {
      params.startDate = keyboardDateRange.value[0]
      params.endDate = keyboardDateRange.value[1]
    } else if (keyboardTimeRange.value === 'week') {
      if (keyboardWeekRange.value) {
        params.startWeek = keyboardWeekRange.value
      }
      if (keyboardWeekRangeEnd.value) {
        params.endWeek = keyboardWeekRangeEnd.value
      }
    }

    // 根据对比模式添加相应的参数（符合后端API规范）
    if (keyboardCompareMode.value === 'personal') {
      if (keyboardSelectedUser.value) {
        params.userId = keyboardSelectedUser.value
      }
    } else if (keyboardCompareMode.value === 'compare') {
      if (keyboardUser1.value) {
        params.userId = keyboardUser1.value
      }
      if (keyboardUser2.value) {
        params.compareUserId = keyboardUser2.value
      }
    } else if (keyboardCompareMode.value === 'vs_dept') {
      if (keyboardSelectedUser.value) {
        params.userId = keyboardSelectedUser.value
      }
      if (keyboardSelectedDept.value) {
        params.departmentId = keyboardSelectedDept.value
      }
    }

    const response = await dashboardService.getBehaviorTrends(params)

    if (response.success) {
      keyboardTrendData.value = response.data
    }
  } catch (error) {
    console.error('加载键盘趋势数据失败:', error)
  }
}

// 加载鼠标热力图数据
const loadMouseHeatmapData = async () => {
  try {
    const params = {
      timeRange: mouseTimeRange.value,
      compareMode: mouseCompareMode.value
    }

    // 添加日期和周范围筛选参数
    if (mouseTimeRange.value === 'day' && mouseDateRange.value && mouseDateRange.value.length === 2) {
      params.startDate = mouseDateRange.value[0]
      params.endDate = mouseDateRange.value[1]
    } else if (mouseTimeRange.value === 'week') {
      if (mouseWeekRange.value) {
        params.startWeek = mouseWeekRange.value
      }
      if (mouseWeekRangeEnd.value) {
        params.endWeek = mouseWeekRangeEnd.value
      }
    }

    // 根据对比模式添加相应的参数（符合后端API规范）
    if (mouseCompareMode.value === 'personal') {
      if (mouseSelectedUser.value) {
        params.userId = mouseSelectedUser.value
      }
    } else if (mouseCompareMode.value === 'compare') {
      if (mouseUser1.value) {
        params.userId = mouseUser1.value
      }
      if (mouseUser2.value) {
        params.compareUserId = mouseUser2.value
      }
    } else if (mouseCompareMode.value === 'vs_dept') {
      if (mouseSelectedUser.value) {
        params.userId = mouseSelectedUser.value
      }
      if (mouseSelectedDept.value) {
        params.departmentId = mouseSelectedDept.value
      }
    }

    const response = await dashboardService.getMouseHeatmap(params)

    if (response.success) {
      mouseHeatmapData.value = response.data
    }
  } catch (error) {
    console.error('加载鼠标热力图数据失败:', error)
  }
}

// 当筛选条件改变时重新加载数据
const handleKeyboardFilterChange = async () => {
  await loadKeyboardTrendData()
}

const handleMouseFilterChange = async () => {
  await loadMouseHeatmapData()
}

// 获取鼠标图例标签
const getMouseLegendLabel = (type) => {
  if (type === 'primary') {
    if (mouseCompareMode.value === 'personal') {
      const user = availableUsers.value.find(u => u.id === mouseSelectedUser.value)
      return user ? user.name : '当前用户'
    } else if (mouseCompareMode.value === 'compare') {
      const user = availableUsers.value.find(u => u.id === mouseUser1.value)
      return user ? user.name : '用户1'
    } else if (mouseCompareMode.value === 'vs_dept') {
      const user = availableUsers.value.find(u => u.id === mouseSelectedUser.value)
      return user ? user.name : '当前用户'
    }
    return '当前用户'
  } else if (type === 'compare') {
    if (mouseCompareMode.value === 'compare') {
      const user = availableUsers.value.find(u => u.id === mouseUser2.value)
      return user ? user.name : '用户2'
    } else if (mouseCompareMode.value === 'vs_dept') {
      const dept = availableDepts.value.find(d => d.id === mouseSelectedDept.value)
      return dept ? dept.name + '平均' : '部门平均'
    }
    return '对比数据'
  }
  return ''
}

// 加载详细统计数据
const loadBehaviorStats = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    const response = await behaviorAPI.getBehaviorLogs(params)

    if (response && response.code === 200) {
      behaviorStats.value = response.data.list || []
      pagination.total = response.data.total || 0
    } else {
      behaviorStats.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('加载行为统计数据失败:', error)
    ElMessage.error('加载统计数据失败: ' + error.message)
    behaviorStats.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 加载用户数据（使用客户端数据作为用户选项）
const loadUsers = async () => {
  try {
    // 确保客户端数据已加载
    await clientsStore.loadClients()

    // 将客户端转换为用户选项
    const clientsArray = Array.from(clientsStore.clients.values())
    availableUsers.value = clientsArray.map(client => ({
      id: client.id,
      name: client.name || `客户端-${client.id}`,
      username: client.hostname || `client-${client.id}`,
      department: client.department?.name || '未分配部门'
    }))

    console.log('加载的用户数据:', availableUsers.value)
  } catch (error) {
    console.error('加载用户数据失败:', error)
    // 如果加载失败，使用模拟数据
    availableUsers.value = [
      { id: 1, name: '张三', username: 'zhangsan', department: '技术部' },
      { id: 2, name: '李四', username: 'lisi', department: '市场部' },
      { id: 3, name: '王五', username: 'wangwu', department: '技术部' }
    ]
  }
}

// 加载部门数据
const loadDepartments = async () => {
  try {
    const response = await departmentsService.getDepartmentOptions()
    if (response.success) {
      availableDepts.value = response.data
    } else {
      // 如果API调用失败，使用模拟数据
      availableDepts.value = [
        { id: 1, name: '技术部', label: '技术部' },
        { id: 2, name: '市场部', label: '市场部' },
        { id: 3, name: '运营部', label: '运营部' }
      ]
    }
    console.log('加载的部门数据:', availableDepts.value)
  } catch (error) {
    console.error('加载部门数据失败:', error)
    // 如果加载失败，使用模拟数据
    availableDepts.value = [
      { id: 1, name: '技术部', label: '技术部' },
      { id: 2, name: '市场部', label: '市场部' },
      { id: 3, name: '运营部', label: '运营部' }
    ]
  }
}





// 导出数据
const exportData = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要导出当前筛选条件下的行为数据吗？',
      '确认导出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 构建导出参数，使用与查询相同的参数格式
    const params = {
      timeRange: 'all',
      format: 'excel'
    }

    // 调用导出API
    const response = await behaviorAPI.exportData(params)

    if (response && response.code === 200) {
      // 如果返回的是blob数据，直接下载
      if (response instanceof Blob) {
        const url = window.URL.createObjectURL(response)
        const link = document.createElement('a')
        link.href = url
        link.download = `行为分析数据_${new Date().toISOString().split('T')[0]}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } else {
        // 如果返回的是JSON数据，转换为CSV下载
        const csvContent = convertToCSV(response.data)
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `行为分析数据_${new Date().toISOString().split('T')[0]}.csv`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }

      ElMessage.success('数据导出成功')
    } else {
      throw new Error(response.message || '导出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出数据失败:', error)
      ElMessage.error('导出失败: ' + error.message)
    }
  }
}

// 转换数据为CSV格式
const convertToCSV = (data) => {
  if (!data || data.length === 0) return ''

  // CSV头部
  const headers = ['ID', '客户端名称', '主机名', '时间戳', '键盘操作次数', '鼠标操作次数', '活跃时间(秒)', '空闲时间(秒)']

  // CSV内容
  const csvContent = [
    headers.join(','),
    ...data.map(row => [
      row.id || row.ID || '',
      row.client_name || row.ClientName || '',
      row.hostname || row.Hostname || '',
      new Date(row.timestamp || row.Timestamp).toLocaleString(),
      row.keyboard_count || row.KeyboardCount || 0,
      row.mouse_count || row.MouseCount || 0,
      row.active_time || row.ActiveTime || 0,
      row.idle_time || row.IdleTime || 0
    ].join(','))
  ].join('\n')

  // 添加BOM以支持中文
  return '\uFEFF' + csvContent
}

// 组件挂载时初始化
onMounted(async () => {
  // 加载基础数据
  await Promise.all([
    clientsStore.loadClients(),
    loadUsers(),
    loadDepartments()
  ])

  // 设置默认选择的用户
  if (availableUsers.value.length > 0) {
    // 设置图表的默认用户
    keyboardSelectedUser.value = availableUsers.value[0]?.id
    mouseSelectedUser.value = availableUsers.value[0]?.id

    // 设置筛选表单的默认用户
    filterForm.selectedUser = availableUsers.value[0]?.id
    filterForm.selectedUsers = availableUsers.value.slice(0, 2).map(u => u.id)
  }

  // 加载图表数据
  await loadKeyboardTrendData()
  await loadMouseHeatmapData()

  // 加载统计数据
  await loadBehaviorStats()
})

// 组件卸载时清理
onUnmounted(() => {
  // 清理工作（如果需要）
})
</script>

<style scoped>
.behavior-analysis-page {
  max-width: 1600px;
  margin: 0 auto;
  padding: 0 16px;
  background: #f8fafc;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
  padding: 24px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  font-weight: 300;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  border: none;
}

.heatmap-card {
  margin: 24px 0;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.charts-row {
  margin-bottom: 32px;
}

.chart-card {
  margin-bottom: 24px;
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  overflow: hidden;
  background: white;
}

.chart-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.chart-content {
  padding: 24px;
  background: linear-gradient(to bottom, #ffffff 0%, #f8fafc 100%);
}

.chart-legend {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 24px;
  padding: 12px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #4a5568;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  background: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.legend-color {
  width: 14px;
  height: 14px;
  border-radius: 3px;
  display: inline-block;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.chart-area {
  margin-bottom: 16px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f7fafc 100%);
  box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
  overflow: hidden;
}

.chart-x-axis {
  display: flex;
  justify-content: space-between;
  padding: 0 24px;
  font-size: 13px;
  color: #718096;
  font-weight: 500;
  background: #f7fafc;
  padding-top: 8px;
  padding-bottom: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px;
}

.el-row {
  margin-bottom: 24px;
}

.el-form--inline .el-form-item {
  margin-right: 24px;
  margin-bottom: 16px;
}

.el-table {
  margin-top: 24px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}

/* 自定义Element Plus组件样式 */
:deep(.el-card__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 2px solid #e2e8f0;
  padding: 20px 24px;
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-select) {
  border-radius: 8px;
}

:deep(.el-date-editor) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

/* SVG数据点样式 */
:deep(.data-point) {
  transition: all 0.2s ease;
  cursor: pointer;
}

:deep(.data-point:hover) {
  r: 7;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .charts-row {
    margin-bottom: 20px;
  }

  .chart-card {
    margin-bottom: 20px;
  }

  .card-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .behavior-analysis-page {
    padding: 0 8px;
  }

  .page-header {
    margin-bottom: 20px;
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .page-description {
    font-size: 14px;
  }

  .chart-content {
    padding: 16px;
  }

  .chart-legend {
    flex-direction: column;
    gap: 8px;
  }

  .chart-x-axis {
    padding: 0 16px;
    font-size: 11px;
  }
}
</style>
